import axios from "axios";
import { onMounted, reactive, toRefs } from "vue";

export function useRequest(url: string, params: any) {
  const state = reactive({
    query: params.query,
    loading: false,
    error: false,
    data: {}
  });

  const run = async () => {
    state.loading = true;
    state.error = false;

    try {
      const res = await axios.get(url, {
        params: {
          query: state.query
        }
      });

      state.data = res.data;
      state.error = false;
    } catch {
      state.data = {};
      state.error = true;
    }

    state.loading = false;
  };

  onMounted(() => {
    run();
  });

  return {
    ...toRefs(state),
    run
  };
}
